<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" class="num1">
    <select class="select">
        <option value="+">加</option>
        <option value="-">减</option>
        <option value="*">乘</option>
        <option value="/">除</option>
        <option value="%">余</option>
    </select>
    <input type="text" class="num2">
    <button class="btn">计算</button>
    <input type="text" class="result">
</body>
<script>
    // 简易计算器
    var num1Inp = document.getElementsByClassName("num1")[0];
    var num2Inp = document.getElementsByClassName("num2")[0];
    var select = document.getElementsByClassName("select")[0];
    var btn = document.getElementsByClassName("btn")[0];
    var resultInp = document.getElementsByClassName("result")[0];

    /* btn.onclick = function(){
        var num1 = num1Inp.value;
        var num2 = num2Inp.value;
        var opt = select.value;

        console.log(num1,opt,num2);

        var result = null;
        switch(opt){
            case "+":  result = num1*1 + num2*1; break;
            case "-":  result = num1 - num2; break;
            case "*":  result = num1 * num2; break;
            case "/":  result = num1 / num2; break;
            case "%":  result = num1 % num2; break;
        }

        resultInp.value = result;
    } */


    btn.onclick = function () {
        var num1 = num1Inp.value;
        var num2 = num2Inp.value;
        var opt = select.value;

        console.log(num1, opt, num2);

        var result = calc(num1, opt, num2); // 实际参数

        resultInp.value = result;
    }

    // 此时opt就是魔术字符串: 
    // 魔术字符串指的是，在代码之中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。风格良好的代码，应该尽量消除魔术字符串，改由含义清晰的变量代替。
    function calc(num1, opt, num2) {  // 形参
        var result = null;
        switch (opt) {
            case "+": result = num1 * 1 + num2 * 1; break;
            case "-": result = num1 - num2; break;
            case "*": result = num1 * num2; break;
            case "/": result = num1 / num2; break;
            case "%": result = num1 % num2; break;
        }
        return result;
    }

    // 本次调用过程中:
    // "+" 传入到函数中被形参opt接收,进入到switch中和case中的常量进行对比,如果===就执行对应的选择结构语句!!
    // 解析: 被opt接收的"+", 和switch中对比的"+", 本质上并不是同一个加号  => 强行耦合的代码=>魔术字符串
    calc(1, "+", 1);


</script>

</html>